#include "common.h"
#include "msn_msg.h"

msn_msg_t *msn_msg_parse(const char *buf, const int size, msn_session_t *ms)
{
	g_return_val_if_fail(buf, NULL);
	char *token, *last;
	char cmd_line[1024];
	int cmd_len = 0;
	msn_msg_t *msg = NULL;
	int payload = 0;

	cmd_len = msn_line_get(buf, size, cmd_line, 1024);
	if(!cmd_len)
		return NULL;
	msg = g_slice_new0(msn_msg_t);
	msg->sender_passport = g_string_new(NULL);
	msg->sender_display_name = g_string_new(NULL);
	msn_sb_msg_parse(cmd_line, cmd_len, msg->sender_passport, msg->sender_display_name, &payload);
	msg->body = g_string_new_len(buf + cmd_len, payload);
	/* locate user position */
	msg->owner = g_hash_table_lookup(ms->friends, msg->sender_passport);
	g_assert(msg->owner);
	return msg;
}

void msn_msg_clean(msn_msg_t *msg)
{
	g_return_if_fail(msg);
	
	g_string_free_safe(msg->body, 1);
	g_string_free_safe(msg->sender_passport, 1);
	g_string_free_safe(msg->sender_display_name, 1);
	g_slice_free(msn_msg_t, msg);
}

void msn_msg_insert(msn_msg_t *msg, msn_user_t *user)
{
	g_return_if_fail(msg && user);
	
	user->msgs = g_list_prepend(user->msgs, msg);
	debug_log(8, "%s have %d messages\n", user->passport->str, g_list_length(user->msgs));
}

void msn_msg_redirect_start(msn_msg_t *msg)
{
	g_return_if_fail(msg);
	
	/* send XFR */
}

GString *msn_msg_pack(msn_msg_t *msg, int tr_id)
{
	g_return_val_if_fail(msg, NULL);
	GString *out = g_string_new(NULL);
	
	g_string_printf(out, "MSG %d N %d\r\n", tr_id, msg->body->len);
	g_string_append_len(out, msg->body->str, msg->body->len);
	return out;
}
